<template>
  <ul class="todo-main">
    <!-- 根据App传递的todoList遍历生成Item 并向Item传递对应的数据 -->
    <Item v-for="todo in todoList" :key="todo.id" v-bind="todo" />
  </ul>
</template>

<script>
import { v4 as uuidv4 } from "uuid";

import Item from "./Item";
export default {
  name: "List",
  components: {
    Item,
  },
  data() {
    return {
      todoList: [
        { id: uuidv4(), thing: "唱", done: false },
        { id: uuidv4(), thing: "跳", done: false },
        { id: uuidv4(), thing: "篮球", done: false },
      ],
    };
  },

  mounted() {
    //初始化的时候给$bus绑定事件接收 Header传递的数据
    this.$bus.$on("addTodo", (newTodo) => {
      this.todoList.unshift(newTodo);
    });

    //初始化的时候给Footer发送数据
    this.$bus.$emit("getTodo", this.todoList);

    //全选全不选逻辑
    this.$bus.$on("deleteall", (value) => {
      this.todoList = this.todoList.map((item) => {
        return { ...item, done: value };
      });
    });

    //单个切换逻辑
    this.$bus.$on("asignchenked", (value) => {
      this.todoList = this.todoList.map((item) => {
        return item.id === value ? { ...item, done: !item.done } : item;
      });
    });

    //单个删除逻辑
    this.$bus.$on("asigndelete", (value) => {
      //删除提示
      const isDelete = confirm("确定要删除吗")
      if(!isDelete) return

      //过滤掉点击删除地这一个
      this.todoList = this.todoList.filter((item) => {
        return item.id !== value
      })
    });

    //删除选中逻辑
    this.$bus.$on("deleteevery", () => {
      this.todoList = this.todoList.filter((item) => !item.done )
    });



  },

  watch: {
    //因为Footer把List传递的数组深拷贝了 所以List数组改变Footer中不会改变
    //所以监听List中数据的改变重新调用$bus上的addTodo事件把改变后的数组传递给Header
    todoList: {
      deep: true,
      handler() {
        this.$bus.$emit("getTodo", this.todoList);
      },
    },
  },
};
</script>

<style scoped>
/*main*/
.todo-main {
  margin-left: 0px;
  border: 1px solid #ddd;
  border-radius: 2px;
  padding: 0px;
}

.todo-empty {
  height: 40px;
  line-height: 40px;
  border: 1px solid #ddd;
  border-radius: 2px;
  padding-left: 5px;
  margin-top: 10px;
}
</style>